package be.jaisy.osgi.console.ui.client.logreader;

import java.util.Collection;
import java.util.Iterator;

import be.jaisy.osgi.console.service.api.ILogReaderService;
import be.jaisy.osgi.console.service.api.ILogReaderServiceAsync;
import be.jaisy.osgi.console.service.api.to.LogEntryTo;
import be.jaisy.osgi.console.ui.client.OsgiConsole;
import be.jaisy.ui.gwt.client.widget.Sink;
import be.jaisy.ui.gwt.client.widget.table.Table;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.HTMLTable.RowFormatter;

/**
 * Demonstrates the various button widgets.
 */
public class LogReader extends Sink {

	public static SinkInfo init() {
		return new SinkInfo("LogReader", "<p>LogService Reader</p>") {

			public Sink createInstance() {
				return new LogReader();
			}

			public String getColor() {
				return "#2fba10";
			}
		};
	}

	private final ILogReaderServiceAsync service;

	private final Table table;

	private static final String[] headers = new String[] { "Id", "Time", "Level", "Message" };

	public LogReader() {

		// Initialize the service.
		service = (ILogReaderServiceAsync) GWT.create(ILogReaderService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) service;
		endpoint.setServiceEntryPoint(OsgiConsole.MODULE_RELATIVE_PATH);

		table = new Table(headers);
		refreshData();

		initWidget(table);
	}

	public void onShow() {
		refreshData();
	}

	private void refreshData() {
		service.listLog(new AsyncCallback() {
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}

			public void onSuccess(Object result) {
				Collection logEntryTos = (Collection) result;
				RowFormatter rowFormatter = table.getRowFormatter();
				int rowIndex = 1;
				for (Iterator iter = logEntryTos.iterator(); iter.hasNext();) {
					LogEntryTo logEntryTo = (LogEntryTo) iter.next();
					table.setValue(rowIndex, 0, logEntryTo.getBundleId());
					table.setValue(rowIndex, 1, logEntryTo.getTime());
					table.setValue(rowIndex, 2, logEntryTo.getLevel());
					table.setValue(rowIndex, 3, logEntryTo.getMessage());

					if ("ERROR".equals(logEntryTo.getLevel()))
						rowFormatter.setStyleName(rowIndex, "redRow");
					else if ("WARNING".equals(logEntryTo.getLevel()))
						rowFormatter.setStyleName(rowIndex, "yellowRow");
					else if ("INFO".equals(logEntryTo.getLevel()))
						rowFormatter.setStyleName(rowIndex, "blueRow");
					else
						rowFormatter.setStyleName(rowIndex, "tableRow");
					rowIndex++;
				}
			}

		});
	}
}
